package com.tnovoselec.android.travelassistant.activity;

import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;

import com.actionbarsherlock.app.ActionBar;
import com.tnovoselec.android.common.async.Async;
import com.tnovoselec.android.common.async.listener.Outcome;
import com.tnovoselec.android.common.async.notif.NotifierFactory;
import com.tnovoselec.android.favorites.async.DatabaseInitializer;
import com.tnovoselec.android.orm.apptools.OrmLiteBaseFragmentActivity;
import com.tnovoselec.android.travelassistant.Config;
import com.tnovoselec.android.travelassistant.Constant;
import com.tnovoselec.android.travelassistant.R;
import com.tnovoselec.android.travelassistant.async.DownloadWeather;
import com.tnovoselec.android.travelassistant.db.TravelAssistantDatabaseHelper;
import com.tnovoselec.android.travelassistant.fragment.HomeFragment;

public class HomeActivity extends OrmLiteBaseFragmentActivity<TravelAssistantDatabaseHelper> {

	public interface MeteoReadyListener {
		public void onMeteoReady();
	}

	protected static final String TAG = HomeActivity.class.getSimpleName();
	protected static final String CITY = "city";
	protected static final String INITIALIZED = "initialized";
	protected static final String DB_VERSION = "dbversion";

	protected static boolean FREE_RUN = false;

	protected ProgressDialog dialog = null;

	//private Dao<BankomatDto, String> bankomatDao = null;

	private MeteoReadyListener listener;
	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		super.onCreate(savedInstanceState);

		// requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		// setProgressBarIndeterminateVisibility(Boolean.FALSE);

		if (savedInstanceState == null) {
			HomeFragment fragment = new HomeFragment();
			fragment.setArguments(getIntent().getExtras());
			getSupportFragmentManager().beginTransaction().add(android.R.id.content, fragment).commit();
		}

		checkInitDatabase();
		// initMeteoData();
	}

	@Override
	protected void onStart() {
		super.onStart();
		ActionBar bar = getSupportActionBar();
		if (bar != null) {
			// bar.setDisplayHomeAsUpEnabled(true);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		initMeteoData();
	}
	
	@Override
	protected void onPause() {
		//overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		super.onPause();
	}

	private void checkInitDatabase() {
		if (!FREE_RUN) {
			final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
			boolean newdb = preferences.getInt(DB_VERSION, TravelAssistantDatabaseHelper.DATABASE_VERSION) < TravelAssistantDatabaseHelper.DATABASE_VERSION;
			if (!preferences.getBoolean(INITIALIZED, false) || newdb) {
				preferences.edit().putInt(DB_VERSION, TravelAssistantDatabaseHelper.DATABASE_VERSION).commit();
				dialog = ProgressDialog.show(this, "", super.getResources().getText(R.string.please_wait), true);

				Async.doAsync(null, new DatabaseInitializer(this.getHelper()), new Outcome<Void, Boolean>() {

					@Override
					protected void succeeded(Void key, Boolean result) {
						Editor edit = preferences.edit();
						edit.putBoolean(INITIALIZED, true);
						edit.commit();
						dialog.dismiss();
						FREE_RUN = true;

					}

					@Override
					protected void failed(Void key, Throwable error) {
						Log.e(TAG, "Database exception: ", error);
						dialog.dismiss();
					}
				}, NotifierFactory.getBasicNotifier());
			} else {
				FREE_RUN = true;
				// startActivity(new Intent(this, BankomatiMapActivity.class));
			}
		}
	}

	private void initMeteoData() {
		// dialog = ProgressDialog.show(this, "",
		// super.getResources().getText(R.string.please_wait), true, false);
		Log.i(TAG, "fetching meteo data!");
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		long last = prefs.getLong(Constant.METEO_REFRESH_LAST_TIME, -1);
//		if (System.currentTimeMillis() - last < Config.METEO_REFRESH_INTERVAL && last != -1) {
//			return;
//		}
		prefs.edit().putLong(Constant.METEO_REFRESH_LAST_TIME, System.currentTimeMillis()).commit();

		Async.doAsync(null, new DownloadWeather(Config.METEO_URL, this, false), new Outcome<Void, Boolean>() {

			@Override
			protected void failed(Void key, Throwable t) {
				if (dialog != null && dialog.isShowing()) {
					// dialog.dismiss();
				}
				Log.e("Meteo failed!", "" + t.getMessage());
				t.printStackTrace();
			}

			@Override
			protected void succeeded(Void key, Boolean result) {

				if (listener != null) {
					listener.onMeteoReady();
				}

			}
		}, NotifierFactory.newThreadSpecificNotifier(handler));
	}

	public void setListener(MeteoReadyListener listener) {
		this.listener = listener;
	}
	
	@Override
	protected void onDestroy() {
		PreferenceManager.getDefaultSharedPreferences(this).edit().putLong(Constant.METEO_REFRESH_LAST_TIME, -1).commit();
		super.onDestroy();
	}

}
